package one.stand.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.jmp.autocofiguration.util.OssUtil2;
import com.jmp.base.dto.CardSaveRequest;
import lombok.extern.slf4j.Slf4j;
import one.stand.advice.ResultEnum;
import one.stand.event.CardSaveEvent;
import one.stand.event.CardUpdateEvent;
import one.stand.mapper.BusinessCardMapperExt;
import one.stand.mapper.BusinessCardPublicMapper;
import one.stand.mapper.CompanyPlatformMapperExt;
import one.stand.model.*;
import one.stand.request.BusinessCardRequest;
import one.stand.request.CompanyRequest;
import one.stand.response.BusinessCardResponse;
import one.stand.service.*;
import one.stand.service.CompanyService;
import one.stand.service.user.MenuService;
import one.stand.service.user.TokenService;
import one.stand.service.user.UserAdminService;
import one.stand.util.AssertUtil;
import one.stand.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

import static org.springframework.beans.BeanUtils.copyProperties;

/**
 * @author Administrator
 */
@Service
@Slf4j
public class BusinessCardServiceImpl implements BusinessCardService {
    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;


    @Autowired
    private CompanyService companyService;
    @Autowired
    private CompanyServiceService companyServiceService;
    @Autowired
    private CompanyLicenseService companyLicenseService;
    @Autowired
    private BusinessCardMapperExt businessCardMapperExt;
    @Autowired
    private BusinessCardPublicMapper businessCardPublicMapper;
    @Autowired
    private CompanyPlatformMapperExt companyPlatformMapperExt;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createCard(CardSaveRequest request) {
        log.info("创建名片：{}", JSON.toJSONString(request));
        AssertUtil.isFalse(StringUtils.isBlank(request.getPhone()) || request.getStyle() == null, ResultEnum.PARAM_CHECK);
        AssertUtil.nonNull(request.getName(), ResultEnum.PARAM_CHECK, "请输入名称~!");
        AssertUtil.nonNull(request.getPassword(), ResultEnum.PARAM_CHECK, "请输入密码~!");
        AssertUtil.isFalse(StringUtils.isBlank(request.getPersonalWx()) && StringUtils.isBlank(request.getPhone()), ResultEnum.PARAM_CHECK, "请输入手机号码~!");

        // 根据登录人判断是否重复创建
        BusinessCard cardModel = businessCardBaseService.getByUserId(request.getId());
        if (null != cardModel) {
//            AssertUtil.isFalse(AuditStateEnums.APPLY_IN.getCode().equals(cardModel.getAuditState()), "您有名片待审核，请联系企业管理员！");
//            AssertUtil.isFalse(AuditStateEnums.APPLY_FAIL.getCode().equals(cardModel.getAuditState()), "您有名片审核失败，请联系企业管理员");
            AssertUtil.fail(ResultEnum.PARAM_CHECK, "您已有企业名片");
        }

        //查看公司状态是否正常
        final boolean isBoss = Objects.isNull(request.getCompanyId());
        Integer companyId;
        if (isBoss) {

//            AssertUtil.nonNull(request.getLicensePhotos(), ResultEnum.PARAM_CHECK, "请上传企业资质认证");

            CompanyRequest addRequest = new CompanyRequest();
            addRequest.setId(Long.valueOf(request.getId()));
            addRequest.setCompanyKey(request.getCompanyKey());
            addRequest.setCompanyName(request.getCompanyName());
            addRequest.setCompanyLogo(request.getCompanyLogo());
            addRequest.setCompanyNotice(request.getCompanyNotice());
            addRequest.setIndustryId(request.getIndustryId());
            addRequest.setPassword(request.getPassword());
            addRequest.setToken(request.getToken());
            companyId = companyService.addCompany(addRequest, request.isClientJxs(), request.isNoPassword() ? CompanyBaseService.PLATFORM_KEY_HUAYUAN : null);
        } else {
            companyId = request.getCompanyId();
            Company companyModel = companyService.get(request.getCompanyId());
            AssertUtil.nonNull(companyModel, "选择公司不存在~!");
            AssertUtil.isFalse(companyModel.getIsDel().equals(BaseModel.YES_DEL), "公司已解散~!");
            if (!request.isNoPassword()) {
                AssertUtil.isTrue(request.getPassword().equals(companyModel.getPassword()), ResultEnum.PARAM_CHECK, "公司口令不对，请重试~!");
            }
        }

        // 根据电话判断是否重复
        BusinessCard model = businessCardBaseService.get(null, request.getPhone(), null, null);
        AssertUtil.isNull(model, ResultEnum.PARAM_CHECK, "电话号码重复，无法创建~!");

        Integer userId = request.getId();
        if (StringUtils.isBlank(request.getLogo())) {//上传的头像为空就使用微信logo
            request.setLogo(userAdminService.get(userId).getUserImg());
        }

        // 保存名片信息
        BusinessCard inModel = new BusinessCard();
        inModel.setCompanyId(companyId);
        inModel.setPhone(request.getPhone());
        inModel.setStyle(request.getStyle());
        inModel.setName(request.getName());
        inModel.setPersonalWx(request.getPersonalWx());
        inModel.setLogo(request.getLogo());
        inModel.setCompanyWx(request.getCompanyWx());
        inModel.setPhoto(request.getPhoto());
        inModel.setPosition(request.getPosition());
        inModel.setSoundRecording(request.getSoundRecording());
        inModel.setSoundTime(request.getSoundTime());
        inModel.setEmail(request.getEmail());
        inModel.setBriefIntroduction(request.getBriefIntroduction());

        inModel.setCardId(null);
        inModel.setCompanyKey(null);
        inModel.setUserId(request.getId());
        inModel.setCreateTime(DateUtil.currentDate());
        inModel.setIsDel(0);
        inModel.setState(1);
        inModel.setAuditState(!isBoss && request.isNoPassword() ? AUDIT_STATE_NORMAL : AUDIT_STATE_AGREE);
        formatOss(inModel);
        businessCardMapperExt.insertSelective(inModel);

        // 查询公司购买服务数并使用
        companyServiceService.use(companyId);

        if (isBoss) {
            // 添加企业执照
            companyLicenseService.add(companyId, request.getLicensePhotos(), request.isClientJxs() ? 1 : 2);//申请类型：0其他、1经销 2商家
            //企业太阳码
            companyService.saveCompanyCard(companyId, inModel.getCardId());
        } else {
            // init menu
            CompanyPlatform companyPlatform = companyPlatformMapperExt.selectPlatformByCompanyId(companyId);
            if (Objects.nonNull(companyPlatform) && CompanyBaseService.PLATFORM_KEY_HUAYUAN.equals(companyPlatform.getCompanyKey())) {//花园购开通所有权限
                menuService.initCrm(userId, true);
            } else {
                menuService.initCrm(userId, false);
            }
        }

        // 移除当前用户所有登录
        if (!request.isNoPassword()) {
            tokenService.remove(Lists.newArrayList(Long.valueOf(request.getId())));
        }

        applicationContext.publishEvent(new CardSaveEvent(inModel.getCardId(), isBoss, request.isClientJxs(), request.isNoPassword()));
    }

    @Override
    @Transactional
    public void remove(Integer cardId) {
        BusinessCard cardDelete = new BusinessCard();
        cardDelete.setCardId(cardId);
        cardDelete.setIsDel(1);
        int r = businessCardMapperExt.updateByPrimaryKeySelective(cardDelete);
        AssertUtil.isTrue(r == 1, ResultEnum.FAIL);

        BusinessCard card = businessCardMapperExt.selectByPrimaryKey(cardId);
        menuService.remove(card.getUserId());
    }

    @Override
    @Transactional
    public int removeByCompanyId(Integer companyId) {
        return businessCardMapperExt.deleteBusinessCard(companyId, 1);
    }

    @Override
    @Transactional
    public ResultModel<Boolean> updateCard(BusinessCardRequest request) {
        if (request == null || request.getCardId() == null) {
            return ResultModel.checkParamFail();
        }
        AssertUtil.isTrue(StrUtil.length(request.getPhoto()) < 1000, ResultEnum.PARAM_CHECK, "图片过多");
        BusinessCard model = businessCardBaseService.get(null, request.getPhone(), null, request.getCardId());
        AssertUtil.isNull(model, ResultEnum.FAIL, "电话号码重复，无法修改");

        BusinessCard inModel = new BusinessCard();
        copyProperties(request, inModel);
        inModel.setCompanyId(null);
        inModel.setCompanyKey(null);
        formatOss(inModel);
        if (businessCardMapperExt.updateByPrimaryKeySelective(inModel) > 0) {

            applicationContext.publishEvent(new CardUpdateEvent(inModel.getCardId()));

            return ResultModel.success(true);
        }
        return ResultModel.success(false);
    }

    @Override
    @Transactional
    public void updateCardWxcode(Integer cardId, String wxCode) {
        BusinessCard inModel = new BusinessCard();
        inModel.setCardId(cardId);
        inModel.setWxCode(wxCode);
        formatOss(inModel);
        businessCardMapperExt.updateByPrimaryKeySelective(inModel);

        applicationContext.publishEvent(new CardUpdateEvent(inModel.getCardId()));
    }

    @Override
    public void updatePerfectRate(Integer cardId) {
        if (cardId == null) {
            return;
        }
        BusinessCard model = businessCardMapperExt.selectByPrimaryKey(cardId);
        if (model == null) {
            return;
        }
        int rate = 0;
        // 姓名
        if (StringUtils.isNotBlank(model.getName())) {
            rate += 10;
        }
        // 公司
        if (model.getCompanyId() != null) {
            rate += 10;
        }
        // logo
        if (StringUtils.isNotBlank(model.getLogo())) {
            rate += 10;
        }
        // 电话
        if (StringUtils.isNotBlank(model.getPhone())) {
            rate += 10;
        }
        // 个人微信
        if (StringUtils.isNotBlank(model.getPersonalWx())) {
            rate += 10;
        }
        // 公司微信
        if (StringUtils.isNotBlank(model.getCompanyWx())) {
            rate += 10;
        }
        // email
        if (StringUtils.isNotBlank(model.getEmail())) {
            rate += 10;
        }
        // 图片
        if (StringUtils.isNotBlank(model.getPhoto())) {
            rate += 10;
        }
        // 职位
        if (StringUtils.isNotBlank(model.getPosition())) {
            rate += 10;
        }
        // 录音
        if (StringUtils.isNotBlank(model.getSoundRecording())) {
            rate += 5;
        }
        // 个人简介
        if (StringUtils.isNotBlank(model.getBriefIntroduction())) {
            rate += 5;
        }
        BusinessCard modelUpdate = new BusinessCard();
        modelUpdate.setCardId(cardId);
        modelUpdate.setPerfectRate(rate);
        businessCardMapperExt.updateByPrimaryKeySelective(modelUpdate);
    }

    @Override
    public ResultModel getUserCard(BusinessCardRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        BusinessCardModel model = new BusinessCardModel();
        model.setUserId(request.getId().intValue());
        if (request.getUserId() != null) {
            model.setThumbsUserId(request.getUserId());
        } else {
            model.setThumbsUserId(request.getId().intValue());
        }
        model.setState(1);
        BusinessCardModel businessCardModel = businessCardPublicMapper.select(model);
        if (businessCardModel == null) {
            return ResultModel.fail("名片不存在");
        }
        BusinessCardResponse response = new BusinessCardResponse();
        BeanUtils.copyProperties(businessCardModel, response);
        return ResultModel.success(response);
    }

    @Override
    public BusinessCard getByUserId(Integer userId) {
        return businessCardBaseService.getByUserId(userId);
    }

    @Override
    public BusinessCard get(Integer cardId) {
        return businessCardMapperExt.selectByPrimaryKey(cardId);
    }

    private void formatOss(BusinessCard card) {
        card.setLogo(OssUtil2.getWebsiteUrlReplace(card.getLogo()));
        card.setPhoto(OssUtil2.getWebsiteUrlReplace(card.getPhoto()));
        card.setWxTwoCode(OssUtil2.getWebsiteUrlReplace(card.getWxTwoCode()));
        card.setWxCode(OssUtil2.getWebsiteUrlReplace(card.getWxCode()));
    }
}
